import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Form, message, Select, Input, Switch } from 'antd'
import PropTypes from 'prop-types'
import { decomporessListLicenseAndMobileAndBank, formatCaseDataLicense } from '@src/assets/js/tool'
const { Item } = Form
const { Option } = Select
class OperateModal extends Component {
  state = {
    caseDetail: {},
    applicants: [],
    applicantAgents: [],
    respondents: [],
    respondentsAgents: [],
    secretary: {},
    arbitrators: [],
    personList: [],
    type: ''
  }

  formRef = React.createRef()

  // 获取案件详情
  getCaseDetail () {
    return this.$get(`/api/xapc/case/${this.props.caseid}`)
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        formatCaseDataLicense(res.data)
        this.formatByCaseDetail(res.data)
      })
  }

  // 获取案件仲裁员数据
  getCaseArbitrators () {
    return this.$get(`/api/xapc/case/${this.props.caseid}/arbitrator`)
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        decomporessListLicenseAndMobileAndBank(res.data)
        this.setState({
          arbitrators: res.data
        })
      })
  }

  // 根据案件数据初始化可选项
  formatByCaseDetail (data) {
    this.setState({
      applicants: data.applicants.filter(li => li.status),
      applicantAgents: data.applicant_agents,
      respondents: data.respondents.filter(li => li.status),
      respondentsAgents: data.respondents_agents,
      secretary: {
        id: data.processerid,
        name: data.processer
      }
    })
  }

  // 格式化数据
  async initList () {
    const hide = message.loading('加载中', 120)
    Promise.all([this.getCaseDetail(), this.getCaseArbitrators()])
      .then(res => hide())
      .catch(e => hide())
  }

  onFinish (d) {
    d.iscompere = d.iscompere ? 1 : 0
    this.props.onChange(d)
  }

  // 改变仲裁地位
  changeType (v) {
    const c = this.formRef.current
    c.resetFields()
    c.setFieldsValue({
      type: v,
      meetingid: this.props.meetingid,
      hearingroomid: this.props.hearingroomid,
      id: this.props.data.id
    })
    let personList = []
    if (v === '申请人') {
      personList = this.state.applicants
    } else if (v === '被申请人') {
      personList = this.state.respondents
    } else if (v === '申请人代理人') {
      personList = this.state.applicantAgents
    } else if (v === '被申请人代理人') {
      personList = this.state.respondentsAgents
    } else if (v === '仲裁员') {
      personList = this.state.arbitrators
    } else if (v === '仲裁秘书') {
      this.initFormByPerson(v, this.state.secretary)
    }
    this.setState({
      personList,
      type: v
    })
  }

  // 根据人员信息初始化表单数据
  initFormByPerson (t, d) {
    const c = this.formRef.current
    const form = { name: d.name, mobile: d.mobile || '', biz_uid: d.id }
    if (['申请人代理人', '被申请人代理人'].indexOf(t) !== -1) {
      const p = d.party || []
      form.partyid = p.map(li => li.partyid).join()
    }
    c.setFieldsValue(form)
  }

  // 选择人员
  changeName (type, id) {
    const l = this.state.personList
    let o = null
    for (let i = 0; i < l.length; i++) {
      if (l[i].id === id) {
        o = l[i]
        break
      }
    }
    if (!o) {
      return false
    }
    this.initFormByPerson(type, o)
  }

  initData () {
    const c = this.formRef.current
    const d = this.props.data
    this.setState({
      type: d.type
    })
    c.setFieldsValue({
      id: d.id,
      meetingid: this.props.meetingid,
      hearingroomid: this.props.hearingroomid,
      biz_uid: d.biz_uid,
      type: d.type,
      name: d.name,
      mobile: d.mobile,
      iscompere: d.iscompere === 1,
      facecheck_status: d.facecheck_status
    })
  }

  componentDidUpdate (prev) {
    if (!prev.visible && this.props.visible) {
      this.initList()
      setTimeout(() => {
        this.initData()
      }, 0)
    }
  }

  // 渲染姓名项
  renderNameItem () {
    const t = this.state.type
    const p = this.state.personList
    if (['申请人', '申请人代理人', '被申请人', '被申请人代理人', '仲裁员'].indexOf(t) !== -1) {
      return (
        <Select placeholder='请选择人员' onChange={v => this.changeName(t, v)}>
          {p.map((li, i) => <Option key={i} value={li.id}>{li.name}</Option>)}
        </Select>
      )
    }
    return <Input placeholder='请输入姓名' disabled={t === '仲裁秘书'} />
  }

  render () {
    const { id } = this.props.data
    const types = ['申请人', '申请人代理人', '被申请人', '被申请人代理人', '仲裁员', '仲裁秘书', '其他']
    return (
      <Modal
        title={id ? '修改参会人' : '新增参会人'}
        open={this.props.visible}
        onOk={() => this.formRef.current.submit()}
        onCancel={() => this.props.hide()}
        destroyOnClose
      >
        <Form ref={this.formRef} labelCol={{ flex: '108px' }} onFinish={d => this.onFinish(d)}>
          <Item name='id' noStyle><span /></Item>
          <Item name='meetingid' noStyle><span /></Item>
          <Item name='hearingroomid' noStyle><span /></Item>
          <Item name='partyid' noStyle><span /></Item>
          <Item name='biz_uid' noStyle><span /></Item>
          <Item name='type' label='仲裁地位' rules={[{ required: true, message: '仲裁地位不能为空' }]}>
            <Select placeholder='请选择仲裁地位' onChange={v => this.changeType(v)}>
              {types.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
            </Select>
          </Item>
          <Item name='name' label='姓名' rules={[{ required: true, message: '姓名不能为空' }]}>
            {this.renderNameItem()}
          </Item>
          <Item name='mobile' label='手机号' rules={[{ required: true, message: '手机号不能为空' }]}>
            <Input placeholder='请输入手机号' maxLength={11} />
          </Item>
          <Item name='iscompere' label='是否为主持人' valuePropName='checked'>
            <Switch checkedChildren='是' unCheckedChildren='否' />
          </Item>
        </Form>
      </Modal>
    )
  }
}

OperateModal.proptypes = {
  visible: PropTypes.bool,
  data: PropTypes.object,
  hide: PropTypes.func,
  onChange: PropTypes.func,
  hearingroomid: PropTypes.string,
  meetingid: PropTypes.string,
  caseid: PropTypes.string
}

OperateModal.defaultProps = {
  visible: false,
  data: {},
  hide: () => {},
  onChange: () => {},
  hearingroomid: '',
  meetingid: '',
  caseid: ''
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(OperateModal)
